<template>
  <div class="kim-viewer" v-show="shown" :style="boxStyle">
    <img class="kim-viewer-img" :src="src" alt="" @load="load($event)" :style="imgStyle">
    <span class="iconfont icon-close-bold btn-close" @click="shown=false"></span>
  </div>
</template>

<script>

export default {
  name: "viewer",
  data(){
    return {
      count:19900827,
      shown:false,    //是否显示viewer
      src:null,       //图片地址
      originWidth:0,  //记录图片原始宽度
      originHeight:0, //记录图片原始高度
      windowWidth:window.innerWidth,  //窗口宽度
      windowHeight:window.innerHeight, //窗口高度
    }
  },
  methods:{
    open(src) {
      this.src=src;
      this.shown=true;
    },
    close() {
      this.shown=false;
    },
    load(ev) {
      let el = ev.target;
      this.originWidth = el.naturalWidth;
      this.originHeight = el.naturalHeight;
    }
  },
  mounted() {
    let that = this;
    window.addEventListener('resize',function () {
      that.windowWidth = window.innerWidth;
      that.windowHeight = window.innerHeight;
    })
  },
  computed:{
    boxStyle() {
      return {

      };
    },
    imgStyle() {

      //计算缩放
      let sw = this.windowWidth / this.originWidth; //与window宽度的比例
      let sh = this.windowHeight / this.originHeight;//与window高度的比例
      let scale = Math.min(sw, sh); //缩放倍数，选择最小的，以确保能完全显示在屏幕内
      //最多缩放3倍
      if (scale > 3) {
        scale=3;
      }
      scale = scale * 0.9; //不希望全屏填充，所以乘以0.9
      let width = this.originWidth * scale;
      let height = this.originHeight * scale;
      return {
        width:width+'px',
        height:height+'px',
        'min-width':'200px',
        'min-height':'200px',
      }
      //return {}
    }
  }
}
</script>

<style scoped>
.kim-viewer {
  background-color: rgba(0, 0, 0, 0.7);
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  user-select: none;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 99999999;
}
.kim-viewer .btn-close{
  position: absolute;
  right: 0;
  top: 0;
  font-size: 36px;
  color: #d2d2d2;
  background-color: #393939;
  cursor: pointer;
  height: 35px;
  line-height: 35px;
}
.kim-viewer .btn-close:hover{
  background-color: #ce3519;
  color: #ffffff;
}
.kim-viewer .kim-viewer-img{
  /*width: 90%;
  height: 90%;
  object-fit: contain;*/
}

</style>
